//
//  SearchMusicViewController.m
//  FNer
//
//  Created by 王展 on 15/10/24.
//  Copyright (c) 2015年 wangzhan. All rights reserved.
//

#import "SearchMusicViewController.h"
#import "AFNetworking.h"
#import "Music.h"
#import "SearchMusicTableViewCell.h"
#import "MusicDetailViewController.h"
#import "MusicErchDetailModel.h"
#import "MusicPlayerViewController.h"
#import "DBSphereView.h"
@interface SearchMusicViewController ()<UISearchBarDelegate,UISearchControllerDelegate,UISearchDisplayDelegate,UISearchResultsUpdating,UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,retain)UISearchController *searchController;
@property(nonatomic,copy)NSString *searchStr;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,retain)NSMutableArray *musicArray;
@property(nonatomic,retain)UITableView *musicTV;
@property (nonatomic,assign)BOOL isUpLoading;
@property (nonatomic,retain)NSArray *array;
@property (nonatomic, retain)DBSphereView *dbS;
@end

@implementation SearchMusicViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.musicArray = [NSMutableArray array];

    //左侧按钮
    UIImage *leftImage = [UIImage imageNamed:@"导航栏_button_back_用于白和灰.png"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    
    //创建UISearchcontroller
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.navigationItem.titleView = self.searchController.searchBar;
    self.searchController.searchResultsUpdater = self;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.placeholder = @"搜索音乐";
    self.searchController.searchBar.tintColor = [UIColor colorWithRed:43 / 255.0 green:130 /255.0 blue:199 / 255.0 alpha:1];
    self.searchController.searchBar.barStyle = UIBarStyleBlack;
    
    self.searchController.searchBar.showsCancelButton = NO;
    [self.searchController.searchBar sizeToFit];
    
    
 
    //创建搜索音乐页面
    [self createMusicView];
    
    self.dbS =[[DBSphereView alloc]initWithFrame:CGRectMake(40, 100, 320, 320)];
    UIImageView *imageV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MenuBackground"]];
    imageV.frame = CGRectMake(-40, -100, 375, 667) ;
    [_dbS addSubview:imageV];
    [self.view addSubview:_dbS];
    NSMutableArray *btnArray= [NSMutableArray array];
    self.array =@[@"周杰伦",@"刘德华",@"陈奕迅",@"王力宏",@"吴亦凡",@"鹿晗",@"张学友",@"蔡依林",@"王源",@"王杰",@"刘志强",@"韩晓琳",@"叶一闵",@"金鑫亮",@"刘志衫"];
    for (NSInteger i = 0; i < 15; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        [btn setTitle:self.array[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
           btn.titleLabel.font = [UIFont systemFontOfSize:15.];
        btn.frame = CGRectMake(0, 0, 80, 20);
        [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [btnArray addObject:btn];
        [_dbS addSubview:btn];
    }
    
    
    [_dbS setCloudTags:btnArray];

}

//点击左侧按钮触发
-(void)leftButtonAction
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}


- (void)buttonPressed:(UIButton *)btn
{
    self.searchStr = btn.currentTitle;
    [self getSearchData:1];
}





-(void)addFooterRefresh
{
    self.musicTV.footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page ++;
        self.isUpLoading = NO;
        [self getSearchData:self.page];
        
    }];
}

//使用searchBar触发方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    self.searchStr = self.searchController.searchBar.text;
 //   [self addHeaderRefresh];
    [self addFooterRefresh];
    [self getSearchData:1];
}





//获取搜索数据
-(void)getSearchData:(NSInteger )page
{
    [self.dbS removeFromSuperview];
    NSString *url_string = [NSString stringWithFormat:@"http://echosystem.kibey.com/sound/search?keyword=%@&page=%ld",self.searchStr,page];
    
    NSString *urlEncode = [url_string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    [manager.requestSerializer setValue:@"PHPSESSID=jrucucei5f4fksekjvs66p34g4" forHTTPHeaderField:@"Cookie"];
    
    [manager GET:urlEncode parameters:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
        
        
        NSLog(@"%@",responseObject);
        NSMutableDictionary *bigDic = responseObject;
        NSMutableDictionary *resultDic = [bigDic objectForKey:@"result"];
        NSMutableArray *array = [resultDic objectForKey:@"data"];
        
        for (NSMutableDictionary *dic in array) {
            Music *amusic = [[Music alloc] init];
            [amusic setValuesForKeysWithDictionary:dic];
            [self.musicArray addObject:amusic];
        }
        [self.musicTV reloadData];
        [self.musicTV.header endRefreshing];
        [self.musicTV.footer endRefreshing];
        
        if(self.musicArray.count == 0)
        {
            UIAlertView *alert =[[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"呵呵，%@是谁？",self.searchStr] message:nil delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert show];

        }
        
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
    
        NSLog(@"123");
        
    }];
    
}

//创建搜索音乐页面
-(void)createMusicView
{
    self.musicTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.musicTV];
    self.musicTV.delegate = self;
    self.musicTV.dataSource = self;
    self.musicTV.separatorStyle = UITableViewCellSeparatorStyleNone;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.musicArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchMusicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[SearchMusicTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    cell.amusic = [self.musicArray objectAtIndex:indexPath.row];
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100 * XHIGHT;
}

//点击TV触发方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    MusicPlayerViewController *play = [MusicPlayerViewController sharePlayerDataHandel];
    MusicErchDetailModel *model =[self.musicArray objectAtIndex:indexPath.row];
    play.song_id = [model.id integerValue];
    play.allMusicArray = self.musicArray;
    play.indexRow = indexPath.row;
    play.navigationItem.title = model.name;
    play.isLocal = NO;
    [self.navigationController pushViewController:play animated:YES];
    
    [self.musicTV deselectRowAtIndexPath:indexPath animated:YES];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
